<template>
    <div class="tableContent" style="margin-bottom: 20px;">
        <p class="sub-title">{{$t('预计收益')}}</p>
        <Table class="resizable-table"
               @on-column-width-resize="(a,b,c,d)=>{onColumnWidthResize(a,b,c,d,this.customCacheKeySpecIn)}"
               :columns="columns" :data="dataSource" border>
            <template slot-scope="{ row,index }" slot="action">
                <div class="ivu-table-cell-slot" v-if="!disabled">
                    <span class="operationBtn" v-if="row.operation ==='action'" @click="addItem">{{ $t('新增') }}</span>
                    <span v-if="row.operation !=='action' && row.status!=1" class="operationBtn"
                          @click="removeItem(index)">{{ $t('删除') }}</span>
                    <span v-if="row.operation !=='action' && !row.edit " class="operationBtn"
                          @click="editItem(index)">{{ row.edit ? $t('更新') : $t('编辑') }}</span>
                    <span v-if="row.operation !=='action' && row.edit " class="operationBtn"
                          @click="saveItem(index)">{{ $t('提交') }}</span>
                    <span v-if="row.operation !=='action' && row.edit " class="operationBtn"
                          @click="cancelSaveItem(index)">{{ $t('取消') }}</span>
                </div>
            </template>
            <template slot-scope="{ row,index }" slot="slot2">
                <DatePicker @on-change="onDateChange" :start-date="new Date()" :options="{disabledDate}" format="yyyy"
                            transfer
                            v-model="firstDate"
                            v-if="row.operation !=='action'  && row.edit && index==0"
                            type="year" :placeholder="$t('请选择')"></DatePicker>
                <p class="" style="text-align: left" v-else v-show="row.operation !=='action'">
                    {{ dataSource[index].estimatedTime }}</p>
            </template>
            <template slot-scope="{ row,index }" slot="slot3">
                <InputNumber
                    class="prependMoneyIcon tableInputNumberbr"
                    style="width: 100%" max="999999999"
                    clearable type="number"
                    number
                    v-if="row.operation !=='action'  && row.edit"
                    v-model.number="dataSource[index].estimatedBenefits"
                    :placeholder="$t('请输入')"
                    :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                    :parser="value => value.replace(/k\￥\s?|(,*)/g, '')"/>
                <p class="breakSpaces" style="text-align: left" v-else v-show="dataSource[index].estimatedBenefits">k￥{{ dataSource[index].estimatedBenefits }}</p>
            </template>
            <template slot-scope="{ row,index }" slot="slot4">
                <Input maxlength="200" v-model.trim="dataSource[index].remark" :placeholder="$t('请输入')"
                       v-if="row.operation !=='action'  && row.edit"/>
                <p class="breakSpaces" style="text-align: left" v-else>{{ dataSource[index].remark }}</p>
            </template>
            <template slot-scope="{ row,index }" slot="index">
                <span v-if="row.operation !=='action'">{{ index + 1 }}</span>
            </template>
        </Table>
    </div>
</template>
<script>
const totalComlumns = {remark: "", operation: "action", estimatedTime: "", estimatedBenefits: ""}
import mixins from './mixins'
import moment from 'moment'

export default {
    name: "estimatedRevenueTable",
    mixins: [mixins],
    props: ['disabled', 'list', 'bdgAmount'],
    data() {
        return {
            dataSource: [{...totalComlumns}],
            columns: [
                {
                    title: this.$t('序号'),
                    slot: "index",
                    resizable: true,tooltip: true,
                    width: 80
                },
                {
                    title: this.$t('年份'),
                    key: "estimatedTime",
                    slot: "slot2",
                    resizable: true,tooltip: true,
                    width: 150,
                    renderHeader: (h) => {
                        return h('div', [
                            h('span', {
                                domProps: {
                                    innerHTML: this.$t('年份')
                                },
                                attrs: {
                                    class: "required "
                                }
                            }),
                        ])
                    }
                },
                {
                    title: this.$t('预计收益'),
                    key: "estimatedBenefits",
                    slot: "slot3",
                    resizable: true,tooltip: true,
                    renderHeader: (h) => {
                        return h('div', [
                            h('span', {
                                domProps: {
                                    innerHTML: this.$t('预计收益')
                                },
                                attrs: {
                                    class: "required "
                                }
                            }),
                        ])
                    }
                },
                {
                    title: this.$t('备注'),
                    key: "remark",
                    slot: "slot4",
                    resizable: true,tooltip: true,
                    // renderHeader: (h) => {
                    //     return h('div', [
                    //         h('span', {
                    //             domProps: {
                    //                 innerHTML: this.$t('备注')
                    //             },
                    //             attrs: {
                    //                 class: "required "
                    //             }
                    //         }),
                    //     ])
                    // }
                },
                {
                    title: this.$t('操作'),
                    key: "Items",
                    slot: "action",
                    width: 250,
                    align: "center"
                }
            ],
            customCacheKeySpecIn: "customCacheKeySpecIn11",
            firstDate: ""
        }
    },
    mounted() {
        this.getColumnWidth(this.columns, this.customCacheKeySpecIn)
        this.dataSource = []
        if (Array.isArray(this.list) && this.list.length > 0) {
            const _list = this.list.map((item) => {
                item.indexCode = Math.random()
                if (item.isFirst !== 1)
                    item.edit = false
                return item;
            })
            this.dataSource = JSON.parse(JSON.stringify(_list))
        }

        if (!this.disabled)
            this.dataSource.push({...totalComlumns})
        this.copyDataSource = JSON.parse(JSON.stringify(this.dataSource))
    },
    methods: {
        moment,
        onDateChange(value) {
            this.firstDate = value;
            this.dataSource[0]['estimatedTime'] = this.$moment(value).format('YYYY')
        },
        disabledDate(value) {
            return this.$moment(value).format('YYYY') < this.$moment(new Date()).format('YYYY')
        },
        saveItem(index) {
            this.activeIndex = index
            if (!this.dataSource[this.activeIndex].estimatedTime) {
                this.$Message.error(this.$t('请输入'))
                return;
            }
            if (!this.dataSource[this.activeIndex].estimatedBenefits) {
                this.$Message.error(this.$t('请输入'))
                return;
            }
            // if (!this.dataSource[this.activeIndex].remark) {
            //     this.$Message.error(this.$t('请输入'))
            //     return;
            // }
            this.dataSource[this.activeIndex]['edit'] = false

            this.getYearTime()

            this.calculatingBack()

            this.$forceUpdate()

        },
        cancelSaveItem(index) {
            const obj = this.copyDataSource.find(item => {
                if (this.dataSource[index].indexCode === item.indexCode)
                    return item
            })

            if (obj)
                this.dataSource.splice(index, 1, {...obj, edit: false})
            else
                this.dataSource.splice(index, 1)
            this.$forceUpdate()
        },
        checkEditStatus() {
            const obj = this.dataSource.find(item => item.edit)
            if (obj) {
                this.$Message.error(this.$t('请先保存'))
                return true
            } else {
                return false
            }
        },
        editItem(index) {
            if (this.checkEditStatus()) return false
            this.dataSource[index]['edit'] = true
            this.activeIndex = index
            this.copyDataSource = JSON.parse(JSON.stringify(this.dataSource))
            this.$forceUpdate()
        },
        addItem() {
            if (this.getBdgAmountrResult()) return false;
            if (this.checkEditStatus()) return false
            const dataSourceObj = this.dataSource.length > 1 ? this.dataSource[this.dataSource.length - 2] : {}



            const obj = {
                indexCode: Math.random(),
                edit: true,
                estimatedTime: dataSourceObj.estimatedTime / 1 + 1,
                estimatedBenefits: "",
                remark: ""
            }

            if (this.dataSource.length===1){
                const date =  this.$moment().format('YYYY')
                this.firstDate = date
                obj.estimatedTime = date
            }
            this.dataSource.splice(this.dataSource.length - 1, 0, obj)
        },
        removeItem(index) {
            this.dataSource.splice(index, 1)
            this.getYearTime()
            this.calculatingBack()
        },
        getYearTime() {
            if (this.dataSource.length > 1) {
                for (let i = 0; i < this.dataSource.length; i++) {
                    if (i > 0 && i < this.dataSource.length) {
                        this.dataSource[i].estimatedTime = this.dataSource[i - 1].estimatedTime / 1 + 1
                    }
                }
            }
            this.$forceUpdate()
        },
        getBdgAmountrResult() {
            // let total = 0;
            // for (let i = 0; i < this.dataSource.length - 1; i++) {
            //     total = total + this.dataSource[i].estimatedBenefits / 1
            // }
            // return this.bdgAmount <= total
            return false;
        },
        calculatingBack(bdgAmountNum) {
            const bdgAmount = bdgAmountNum || this.bdgAmount;
            let list = JSON.parse(JSON.stringify(this.dataSource))
            list.splice(list.length - 1, 1)
            const value = this.calculatingBackRate(bdgAmount,list);
            this.$emit('change', value);

        },
        getParams() {
            if (this.checkEditStatus()) return false
            let list = JSON.parse(JSON.stringify(this.dataSource))
            list.splice(list.length - 1, 1)
            return list;
        }
    }
}
</script>

<style lang="scss" scoped>
.tableInputNumberbr {
    border: 1px solid #dcdee2;

    /deep/ .ivu-input-number-input {
        border: none;
    }
}
</style>
